import { GenericEnvStore } from "@/modules/dev-env/store/generic-env-store.ts";
import type { LocalVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { ZkMirror } from "@/modules/dev-env/middleware/zookeeper/zk-mirror.ts";
import type { EnvTableAction } from "@/modules/dev-env/store/types.ts";
import { execInTerminal, openInTerminal } from "@/util/system-utils2.ts";
import { noop } from "@/framework/util/warning.ts";
import { openExternal } from "@/util/shell.ts";

export class ZkEnvStore extends GenericEnvStore<ZkEnvStore> {
  constructor() {
    super("zookeeper");
    this.icon = "icon-zookeeper";
    this.pageConfig = {
      showCurrentAction: false,
      showSetting: false,
    };
    this.tableActions = this._tableActions();
  }

  private _tableActions(): EnvTableAction[] {
    return [
      {
        key: "zkServer",
        name: "zkServer",
        icon: "icon-terminal",
        onClick: (version: LocalVersionItem) => execInTerminal("zkServer", { cwd: version.installPath, subPath: ["bin"] }),
      },
      {
        key: "zkCli",
        name: "zkCli",
        icon: "icon-terminal",
        onClick: (version: LocalVersionItem) => execInTerminal("zkCli", { cwd: version.installPath, subPath: ["bin"] }),
      },
      {
        key: "open-in-terminal",
        name: "在终端打开",
        icon: "icon-terminal",
        onClick: (version: LocalVersionItem) => openInTerminal(version.installPath, { subPath: ["bin"] }),
      },
      {
        key: "config",
        name: "编辑配置",
        icon: "icon-setting",
        onClick: async (version: LocalVersionItem) => {
          const cfgFile = path.join(version.installPath, "conf/zoo.cfg");
          if (!(await native.fs.exists(cfgFile))) {
            const cfgSampleFile = path.join(version.installPath, "conf/zoo_sample.cfg");
            await native.fs.copyFile(cfgSampleFile, cfgFile);
          }
          openExternal(cfgFile).catch(noop);
        },
      },
    ];
  }

  protected getMirrors0(): BaseEnvMirror[] {
    return [
      new ZkMirror("aliyun"),
      new ZkMirror("tencent"),
      new ZkMirror("huaweicloud"),
      new ZkMirror("tsinghua"),
      new ZkMirror("apache"),
      // ...
    ];
  }

  protected async getVersionInfo(versionDir: string): Promise<LocalVersionItem | undefined> {
    // apache-zookeeper-3.9.4-bin
    const folderName = path.basename(versionDir);
    if (!folderName.startsWith("apache-zookeeper-")) return undefined;
    const zkServer = path.join(versionDir, "bin/zkServer.sh");
    if (!(await native.fs.exists(zkServer))) return undefined;

    const [, , version] = folderName.split("-");
    return Promise.resolve({
      version: version,
      installPath: versionDir,
    });
  }
}
